#!/usr/bin/env python3
"""
LightPort 高级使用示例
"""

import asyncio
import sys
from pathlib import Path
import json

# 添加项目根目录到路径
sys.path.insert(0, str(Path(__file__).parent.parent))

from core.scanner import LightScanner
from utils.output import OutputFormatter
from rich.console import Console

console = Console()

async def cidr_scan_example():
    """CIDR网段扫描示例"""
    
    scanner = LightScanner(
        stealth_mode=True,
        bypass_enabled=True,
        timeout=3,
        max_threads=100,
        verbose=False
    )
    
    # 扫描本地网段
    targets = ["192.168.1.0/30"]  # 4个IP地址
    ports = [22, 80, 443, 3389]
    
    console.print("[bold blue]扫描CIDR网段示例[/bold blue]")
    
    results = await scanner.scan_targets(targets, ports)
    
    # 显示结果
    formatter = OutputFormatter(console)
    formatter.display_results(results, 0)  # 持续时间设为0
    
    # 保存结果
    with open("cidr_scan_results.json", "w") as f:
        json.dump(results, f, indent=2, default=str)
    
    console.print("\n[green]结果已保存到: cidr_scan_results.json[/green]")

async def bypass_example():
    """防火墙绕过示例"""
    
    scanner = LightScanner(
        stealth_mode=True,
        bypass_enabled=True,
        timeout=5,
        max_threads=50,
        verbose=True
    )
    
    # 模拟有防火墙保护的目标
    targets = ["scanme.nmap.org"]  # Nmap官方测试目标
    ports = [22, 80, 443, 8080]
    
    console.print("\n[bold red]防火墙绕过扫描示例[/bold red]")
    
    results = await scanner.scan_targets(targets, ports)
    
    # 分析绕过效果
    bypassed_ports = []
    for target_ports in results['results'].values():
        for port_info in target_ports:
            if 'bypass_method' in port_info:
                bypassed_ports.append({
                    'port': port_info['port'],
                    'method': port_info['bypass_method']
                })
    
    if bypassed_ports:
        console.print("\n[green]成功绕过防火墙的端口:[/green]")
        for item in bypassed_ports:
            console.print(f"  端口 {item['port']}: {item['method']}")
    else:
        console.print("\n[yellow]未检测到防火墙或无需绕过[/yellow]")

async def comprehensive_scan_example():
    """综合扫描示例"""
    
    scanner = LightScanner(
        stealth_mode=True,
        bypass_enabled=True,
        spoof_ip=None,  # 不伪造IP
        timeout=3,
        max_threads=200,
        verbose=True
    )
    
    # 综合扫描配置
    config = {
        "targets": ["127.0.0.1", "192.168.1.1"],
        "ports": "1-100",
        "output_formats": ["json", "csv"]
    }
    
    console.print("\n[bold cyan]综合扫描示例[/bold cyan]")
    
    # 解析端口范围
    ports = list(range(1, 101))
    
    # 执行扫描
    results = await scanner.scan_targets(config["targets"], ports)
    
    # 生成报告
    report = {
        "scan_config": config,
        "results": results,
        "summary": {
            "total_targets": len(config["targets"]),
            "total_ports": len(ports),
            "open_ports": sum(len(ports) for ports in results["results"].values()),
            "services_found": list(set(
                port_info.get("service", "unknown") 
                for ports in results["results"].values() 
                for port_info in ports
            ))
        }
    }
    
    # 保存不同格式
    for fmt in config["output_formats"]:
        filename = f"comprehensive_scan.{fmt}"
        if fmt == "json":
            with open(filename, "w") as f:
                json.dump(report, f, indent=2, default=str)
        elif fmt == "csv":
            from utils.output import OutputFormatter
            formatter = OutputFormatter(console)
            formatter.export_csv(results, filename)
    
    console.print(f"\n[green]综合扫描完成，结果已保存到: {config['output_formats']}[/green]")

if __name__ == "__main__":
    print("LightPort 高级使用示例")
    print("=" * 50)
    
    try:
        # 运行各种示例
        asyncio.run(cidr_scan_example())
        asyncio.run(bypass_example())
        asyncio.run(comprehensive_scan_example())
        
    except KeyboardInterrupt:
        print("\n示例被中断")
    except Exception as e:
        print(f"错误: {e}")
        import traceback
        traceback.print_exc()
